// 格式化工具函数

export function formatTimestamp(): string {
  return new Date().toLocaleString('zh-CN');
}

export function formatTokenCount(count: number): string {
  if (count < 1000) {
    return `${count} tokens`;
  } else if (count < 1000000) {
    return `${(count / 1000).toFixed(1)}K tokens`;
  } else {
    return `${(count / 1000000).toFixed(1)}M tokens`;
  }
}

export function formatDuration(startTime: number): string {
  const duration = Date.now() - startTime;
  if (duration < 1000) {
    return `${duration}ms`;
  } else {
    return `${(duration / 1000).toFixed(1)}s`;
  }
}

export function formatError(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }
  if (typeof error === 'string') {
    return error;
  }
  return '未知错误';
}

export function formatToolCall(name: string, args: Record<string, any>): string {
  return `🔧 调用工具: ${name}\n📋 参数: ${JSON.stringify(args, null, 2)}`;
}

export function formatToolResult(name: string, result: string, duration?: number): string {
  let output = `✅ 工具 ${name} 执行完成`;
  if (duration) {
    output += ` (${formatDuration(duration)})`;
  }
  output += `\n📊 结果:\n${result}`;
  return output;
}

export function wrapText(text: string, width: number = 80): string {
  const words = text.split(' ');
  const lines: string[] = [];
  let currentLine = '';

  for (const word of words) {
    if ((currentLine + word).length <= width) {
      currentLine += (currentLine ? ' ' : '') + word;
    } else {
      if (currentLine) {
        lines.push(currentLine);
      }
      currentLine = word;
    }
  }
  
  if (currentLine) {
    lines.push(currentLine);
  }

  return lines.join('\n');
}

export function highlightCode(text: string): string {
  // 简单的代码高亮（可以扩展）
  return text
    .replace(/`([^`]+)`/g, '\x1b[36m$1\x1b[0m') // 内联代码
    .replace(/```(\w+)?\n([\s\S]*?)```/g, '\x1b[90m```$1\n\x1b[36m$2\x1b[90m```\x1b[0m'); // 代码块
}

export function colorizeOutput(text: string, type: 'success' | 'error' | 'warning' | 'info' = 'info'): string {
  const colors = {
    success: '\x1b[32m', // 绿色
    error: '\x1b[31m',   // 红色
    warning: '\x1b[33m', // 黄色
    info: '\x1b[34m'     // 蓝色
  };
  
  const reset = '\x1b[0m';
  return `${colors[type]}${text}${reset}`;
}
